#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include<sys/wait.h>
#include <string.h>
void writer(int wfd)
{
    int cnt=0;
    char ch[10]="abcdef";
    while(1)
    {
        char buffer[20]={0};
        snprintf(buffer,sizeof(buffer),"%s %d",ch,cnt);
        write(wfd,buffer,strlen(buffer));
        cnt++;
        sleep(1);
    }
    


    // char ch = 'A';
    // int cnt = 1;
    // while (1)
    // {
    //     write(wfd, &ch, 1);
    //     printf("%d ", cnt);
    //     fflush(stdout);
    //     cnt++;
    // }

    // sleep(100);
    //  const char *str = "i am child,this is the ";
    //  int cnt = 0;
    //  char buffer[128] = {0};
    //  while (1)
    //  {
    //      snprintf(buffer, sizeof(buffer), "%s%d message", str, cnt);
    //      write(wfd, buffer, strlen(buffer));
    //      sleep(1);
    //      cnt++;
    //  }
}
void reader(int rfd)
{
    int cnt=5;
    while(cnt--)
    {
        char buffer[1024] = {0};
        read(rfd, buffer, sizeof(buffer));
        printf("I am father,I get a message:%s\n", buffer);
    }
    
    // while (1)
    // {
    //     char buffer[1024] = {0};
    //     int ret=read(rfd, buffer, sizeof(buffer));
    //     if(ret==0)break;
    //     printf("I am father,I get a message:%s\n", buffer);
    // }
}

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n < 0)
        return 1;
    pid_t id = fork();
    if (id == 0)
    {
        // 子进程负责w
        close(pipefd[0]);
        writer(pipefd[1]);
        exit(0);
    }

    // 父进程负责r
    close(pipefd[1]);
    reader(pipefd[0]);
    close(pipefd[0]);
int status=0;
    waitpid(id,&status,0);
    printf("exit signal is %d\n",status&0x7f);
    return 0;
}